package com.jwaoo.chat.activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.inputmethod.InputMethodManager;
import com.dx.as.ToolBarOptions;
import com.dx.as.UI;
import com.jwaoo.chat.ChatConstants;
import com.jwaoo.chat.ChatHelpter;
import com.jwaoo.chat.Message;
import com.jwaoo.chat.R;
import com.jwaoo.chat.UserInfo;
import com.jwaoo.chat.activity.presenter.P2PPresenter;
import com.jwaoo.chat.session.Extras;
import com.jwaoo.chat.session.ModuleProxy;
import com.jwaoo.chat.session.actions.GiftAction;
import com.jwaoo.chat.session.actions.ImpressionAction;
import com.jwaoo.chat.session.actions.VideoChatAction;
import com.jwaoo.chat.session.actions.BaseAction;
import com.jwaoo.chat.session.actions.Container;
import com.jwaoo.chat.session.actions.ImageAction;
import com.jwaoo.chat.session.actions.SnapChatAction;
import com.jwaoo.chat.session.actions.VideoAction;
import com.jwaoo.chat.session.actions.VoiceChatAction;
import com.jwaoo.chat.session.avchat.MyDialogActivity;
import com.jwaoo.chat.session.input.InputPanel;
import com.jwaoo.chat.session.list.MessageListPanelEx;
import com.jwaoo.media.dialog.CustomAlertDialog;
import java.util.ArrayList;
import java.util.List;

/**
 * 点对点聊天界面
 * <p/>
 */
public class P2PMessageActivity  extends UI implements IP2PView{

    protected InputPanel inputPanel;
    protected MessageListPanelEx messageListPanel;
    private MessageReiceiver messageReiceiver;
    private List<Integer> itemIndex = new ArrayList<>();
    private P2PPresenter p2PRepository;
    private UserInfo userInfo;
    private int friend;
    private ToolBarOptions toolBarOptions = new ToolBarOptions();
    private Container container;
    public static void start(Context context, int contactId) {
        Intent intent = new Intent();
        intent.putExtra(Extras.EXTRA_ACCOUNT, contactId);
        intent.setClass(context, P2PMessageActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    protected void onActivityCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_nim_message);
        friend = getIntent().getIntExtra(Extras.EXTRA_ACCOUNT,0);
        p2PRepository = new P2PPresenter(this,this);
        container = new Container(this, friend,proxy);
        if (inputPanel == null) {
            inputPanel = new InputPanel(container,getActionList());
        }
        p2PRepository.getContactInfo(friend);
        p2PRepository.getSendFailedMessage(friend);
        initRecieiver();

        if (messageListPanel == null) {
            messageListPanel = new MessageListPanelEx(container,null, false, false);
        }else {
            messageListPanel.reload(null);
        }
    }


    @Override
    public void getUserInfo(final UserInfo userInfo) {
        this.userInfo = userInfo;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                toolBarOptions.titleString = userInfo.getNickname();
                setToolbar(toolBarOptions);
                messageListPanel.setAvatar(userInfo.getAvatar());
            }
        });
    }

    @Override
    public void onSendFailedMessages(List<Message> list) {

        if (list != null && !list.isEmpty()){
            for (Message message : list){
//                proxy.sendMessage(message);
                itemIndex.add(message.getMsgid());
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (inputPanel != null) {
            inputPanel.onDestroy();
        }
        ChatHelpter.currentSessionId = 0;
        unregisterReceiver(messageReiceiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        ChatHelpter.currentSessionId = friend;

    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onPause() {
        super.onPause();
        inputPanel.onPause();
        messageListPanel.onPause();

    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    private ImageAction imageAction = new ImageAction();
    private VideoAction videoAction = new VideoAction();
    // 操作面板集合
    protected List<BaseAction> getActionList() {
        List<BaseAction> actions = new ArrayList<>();
        actions.add(new VideoChatAction());
        actions.add(new VoiceChatAction());
        actions.add(new SnapChatAction());
        actions.add(new GiftAction());
        actions.add(imageAction);
        actions.add(videoAction);
        actions.add(new ImpressionAction());
        return actions;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        inputPanel.onActivityResult(requestCode, resultCode, data);
//        messageListPanel.onActivityResult(requestCode, resultCode, data);
    }

    private ModuleProxy proxy = new ModuleProxy() {
        @Override
        public boolean sendMessage(Message msg) {
            itemIndex.add(msg.getMsgid());
            if (userInfo != null){
                msg.setNickname(userInfo.getNickname());
                msg.setAvtar(userInfo.getAvatar());
            }
            messageListPanel.onMsgSend(msg);
            return true;
        }

        @Override
        public void showError(int id) {
            showSnackBar(getResources().getString(id));
        }

        @Override
        public void onInputPanelExpand() {
            messageListPanel.scrollToBottom();
        }

        @Override
        public void shouldCollapseInputPanel() {
            hideKeyboard();
            inputPanel.hideMuneLayout();
        }

        @Override
        public boolean isLongClickEnabled() {
            return false;
        }

        @Override
        public void openSnapView() {
            inputPanel.showSnapView();
        }

        @Override
        public void showCameraSelector() {
            onShowCameraSelector();
        }

        @Override
        public void onLoadMessages(int key, Message message) {
            itemIndex.add(key);
        }


    };


    private void hideKeyboard(){
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    @Override
    public void onBackPressed() {
        if (!inputPanel.hideBottomLayot()){
            showKeyboard(false);
            finish();
        }
    }

    private void initRecieiver(){
        messageReiceiver = new MessageReiceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ChatConstants.ACTION_MESSAGE);
        registerReceiver(messageReiceiver, intentFilter);
    }
    private class MessageReiceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            boolean type = intent.getBooleanExtra(Extras.EXTRA_MESSAGE_HIDE_KEY_BOARD,false);
            if (type) {
                hideKeyboard();
                return;
            }

            Message message = (Message) intent.getSerializableExtra(Extras.EXTRA_MESSAGE);

            if (itemIndex.contains(message.getMsgid())){
                messageListPanel.refreshMessageList(message);
            }else{
                messageListPanel.onMsgSend(message);
                itemIndex.add(message.getMsgid());
            }
        }
    }


    private void onShowCameraSelector(){
        CustomAlertDialog dialog = new CustomAlertDialog(this);
        dialog.addItem(getResources().getString(R.string.shot_video),new CustomAlertDialog.onSeparateItemClickListener(){
            @Override
            public void onClick() {
                videoAction.chooseVideoFromCamera();
            }
        });
        dialog.addItem(getResources().getString(R.string.shot),new CustomAlertDialog.onSeparateItemClickListener(){
            @Override
            public void onClick() {
                imageAction.pickFromCamrera();
            }
        });
        dialog.addItem(getResources().getString(R.string.input_panel_photo),new CustomAlertDialog.onSeparateItemClickListener() {
            @Override
            public void onClick() {
                imageAction.pickFromLocal();
            }
        });
        dialog.show();
    }

}
